#!/bin/bash
set -euo pipefail
topdir=$(git rev-parse --show-toplevel)
mydir=$(dirname $(readlink -f $0))
tdir="${mydir}/tmp"
mkdir -p "${tdir}"
trap "rm -rfv ${tdir}" EXIT

schema_version="v1"
schema_json="${schema_version}.json"
digest=$(sha256sum "${schema_json}" | awk '{print $1}')
echo "Generating COSA Schema ${schema_version}"

out="${tdir}/cosa_${schema_version}.go"

schematyper=
if test -f ${topdir}/bin/schematyper; then
    schematyper=${topdir}/bin/schematyper
else
    schematyper=$(which schematyper 2>/dev/null || true)
fi
if test -z "${schematyper}"; then
    env GOBIN=${topdir}/bin go install github.com/idubinskiy/schematyper@latest
    schematyper=${topdir}/bin/schematyper
fi

${schematyper} \
    ${topdir}/src/"${schema_version}.json" \
    -o "${out}" \
    --package="builds" \
    --root-type=Build \
    --ptr-for-omit

# Avoid having a filename in generated code since it
# can vary depending on local checkout paths.
sed -e "s|^// generated.*|// generated by 'make schema'\n// source hash: ${digest}|g"  -i ${tdir}/cosa_v1.go

cat > "${tdir}/schema_doc.go" <<EOM
// Generated by ${0}
// Source hash: ${digest}
// DO NOT EDIT

package builds

var generatedSchemaJSON = \`$(< ${schema_json})
\`
EOM

cp -av ${tdir}/*go ${mydir}/../pkg/builds/
